package com.fs.activiti5.handler;

import java.util.Arrays;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.apache.commons.lang3.StringUtils;

import com.fs.base.utils.ApplicationUtils;
import com.fs.flow.pojo.ProcessTaskConfig;
import com.fs.flow.repository.ProcessTaskConfigRepository;

/**
 * @author TiddlerCJ
 *
 */
public class JTaskHandler implements TaskListener {
	private static final long serialVersionUID = 1L;

	public void notify(DelegateTask delegateTask) {
		ProcessTaskConfigRepository repository = (ProcessTaskConfigRepository) ApplicationUtils.getBean("processTaskConfigRepository");
		/**
		 * 动态获取配置流程节点办理人
		 */
		String taskDefinitionId = delegateTask.getTaskDefinitionKey();
		String processKey = delegateTask.getProcessDefinitionId().split(":")[0];
		ProcessTaskConfig config = repository.findByProcessKeyAndTaskId(processKey, taskDefinitionId);
		delegateTask.setAssignee(null);
		if(config!=null){
			String userReg = config.getUserReg();
			if(StringUtils.isNotBlank(userReg)){
				String [] candidateUsers=  userReg.split(",") ;  
				if(candidateUsers.length>1){
					delegateTask.addCandidateUsers(Arrays.asList(candidateUsers));
				}else{
					delegateTask.setAssignee(userReg);
				}
			}
			String roleReg = config.getRoleReg();
			if(StringUtils.isNotBlank(roleReg)){
				if("发起人".equals(roleReg)){
					delegateTask.setAssignee(ApplicationUtils.User().getNickName());
				}
			}
			//String positionReg = config.getPositionReg();
		}else{
			delegateTask.setAssignee("chenjun");
		}
	}
}
